import os
import pprint, pickle
import sys
def get_dict_conv(pkl_name,extractpath,converg_file):
    pkl_file = open(pkl_name, 'rb')
    dict_paras = pickle.load(pkl_file)
    pkl_file.close()
    
    for job_id in dict_paras:
        if dict_paras[job_id]['PASS'] == str(1):
            print job_id
            outcar_path = extractpath  + job_id + '/OUTCAR'
            row_num = int((os.popen("grep -c 'total energy-change' " + outcar_path).read()).strip())
            print row_num
            number = 1
            v_file = open(converg_file,'a')
            v_file.write(job_id)
            #v_file.close()
            while number <= row_num:
                value = (os.popen("grep -n 'total energy-change' "+outcar_path+" |grep -n ''|grep '^"+str(number)+":'|awk -F':' '{print $4}'|awk '{print $1}'").read()).strip()
                change_value = value[-13:]
                print change_value
                #v_file = open(converg_file,'a')
            	v_file.write(','+change_value)
            	#v_file.close()
                number = number + 1
        	#v_file = open(converg_file,'a')
            v_file.write('\n')
            v_file.close()
        else: continue

#DataPath = 'pass_data'

def get_conv(datapath,converg_file):
    for passfile in os.listdir(datapath):
        
        passpath = datapath + '/' + passfile
        row_num = int((os.popen("grep -a -c 'total energy-change' "+passpath+"/OUTCAR").read()).strip())
        #print row_num
        number = 1
        v_file = open(converg_file,'a')
        v_file.write(passfile)
        while number <= row_num:
            value = (os.popen("grep -a -n 'total energy-change' "+passpath+"/OUTCAR |grep -n ''|grep '^"+str(number)+":'|awk -F':' '{print $4}'|awk '{print $1}'").read()).strip()
            change_value = value[-13:]
            #ab_value = abs(float(change_value))
            #print str(number)
            #os.system()
            #v_file = open('converg.txt','a')
            #v_file.write(passfile)
            #print change_value
            v_file.write(','+change_value)
            #v_file.close()
            number = number + 1
        v_file.write('\n')
        v_file.close()


if __name__ == '__main__':
    #DataPath = '/home/lss/vasp_data'
    #ExtractPath = "/home/lss/201711_extract_data/"
    ExtractPath = sys.agrv[1]
    #converg_file = '201711_converg.csv'
    converg_file = sys.agrv[2]
    #pkl_file = '201711_dict_paras.pkl'
    pkl_file = sys.agrv[3]
    #get_conv(DataPath,converg_file)
    get_dict_conv(pkl_file,ExtractPath,converg_file) 
